<?php
namespace app\system\controller;
use app\system\model\Admin as Mod;
use app\system\model\User as UserModel;
use yichenthink\utils\ReturnMsg;

class Admin extends AdminBase {
	// 查询系统管理人员列表

	public function list($trashed = null) {
		$message = '';
		$code = 400;
		// 查询被删除的
		if ($trashed) {
			$data = Mod::onlyTrashed()
				->with(['adminGroup'])
				->visible(['id', 'admin_name', 'create_time', 'update_time', 'group_id', 'group_name', 'create_user_id'])
				->select();
		} else {
			// 查询未删除的
			$data = Mod::with(['adminGroup'])
				->visible(['id', 'admin_name', 'create_time', 'update_time', 'group_id', 'group_name', 'create_user_id'])
				->select();
		}
		if (isset($data[0])) {
			$code = 200;
			$message = '成功';
		} else {
			$message = '没找到数据';
		}
		ReturnMsg::returnMsg($code, $message, $data);
	}
	// 增加数据
	public function add($user_id) {
		$message = '';
		$code = 400;
		$R = UserModel::where('id', $user_id)->find();
		if (Null != $R) {
			$admin = new Mod;
			$admin->admin_name = $R->nickname;
			$admin->id = $user_id;
			$R = $admin->save();
			if (false !== $R) {
				$code = 200;
				$data = $admin::withTrashed()
					->with(['adminGroup'])
					->where('id', $user_id)
					->visible(['id', 'admin_name', 'create_time', 'update_time', 'group_id', 'group_name', 'create_user_id'])
					->find();
				ReturnMsg::returnMsg($code, $message, $data);
			} else {
				$message = '添加失败,请检查用户是否已在管理列表';
			}
		} else {

			$message = '用户不存在';
		}
		ReturnMsg::returnMsg($code, $message);
	}
	// 修改
	public function update($id, $form = []) {

		// ReturnMsg::returnMsg($code = 400, $message = '成功', $form);
		//设置允许修改的字段
		$upfield = ['group_id' => 'group_id', 'state' => 'state', 'admin_name' => 'admin_name'];
		$message = '';
		$user = Mod::where('id', $id)->find();

		if (null != $user) {
			foreach ($upfield as $key => $value) {
				# code...
				if (isset($form[$key]) && !empty($form[$key])) {
					# code...
					$user->$value = $form[$key];
				}
			}
			$R = $user->save();
			if (false !== $R) {

				$code = 200;
			} else {
				$message = '操作失败';
				$code = 400;
			}
		} else {
			$message = '用户不存在';
			$code = 400;
		}
		ReturnMsg::returnMsg($code, $message);
	}
	// 删除
	public function delete($id = 0, $isTrue = false) {

		$user = Mod::withTrashed()->where('id', $id)
			->find();
		$user->delete($isTrue);
		if (0 !== $user) {
			$code = 200;
		} else {
			$code = 400;
		}

		ReturnMsg::returnMsg($code, '', $user);
	}

	//恢复一条
	public function restore($id = 0) {
		$num = 0;
		$user = Mod::onlyTrashed()
			->where('id', $id)
			->find();
		# code...
		if ($user) {
			$num++;
			# code...
			$user->restore();
		}
		// $user = UserModel::restore($list);
		ReturnMsg::returnMsg($code = 200, '成功恢复了' . $num . '条数据');
	}

}
